import { RouteConfig, ComponentCachedRouteConfig } from './types'
import { importer } from '@/components/async-component'

export function supplyRoutes (
  routes: RouteConfig[],
  parentPath = '',
  inheritAuthority?: string[],
): RouteConfig[] {
  return routes.map(route => {
    const config = {
      ...route,
      path: parentPath + route.path,
      authority: route.authority || inheritAuthority,
    }

    if (route.children) {
      config.children = supplyRoutes(
        route.children,
        route.path,
        route.authority
      )
    }

    return config
  })
}

export function flattenRoutes (routes: RouteConfig[]): RouteConfig[] {
  const flattenedRoutes: RouteConfig[] = []

  ;(function recursion (_routes: RouteConfig[]): void {
    _routes.forEach(route => {
      flattenedRoutes.push(route)
      if (route.children) {
        recursion(route.children)
        delete route.children
      }
    })
  })(routes)

  return flattenedRoutes
}

export function generateRouteConfig (routes: RouteConfig[]): ComponentCachedRouteConfig[] {
  return flattenRoutes(supplyRoutes(routes)).map(route => {
    const Component = importer(route.component || route.path)
    return {
      ...route,
      Component,
    }
  })
}

